// pages/pay/order-list/index.js
const apiService = require('../../../utils/api.js');
const auth = require('../../../utils/auth.js');
const setting = require('../../../setting/setting.js');
const app = getApp();

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		statusBarHeight: 44, // 系统状态栏高度
		searchText: '', // 搜索关键字
		activeTab: 0, // 当前选中的Tab索引 0:全部 1:待支付 2:已完成 3:已取消
		tabs: ['全部', '待支付', '已完成', '已取消'],
		orderList: [], // 订单列表
		filteredOrderList: [], // 筛选后的订单列表
		isLoading: false, // 加载状态
		isEmpty: false // 是否为空
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		// 获取系统信息
		this.getSystemInfo();
		
		// 处理状态参数，设置默认选中的Tab
		if (options.status) {
			this.setTabByStatus(options.status);
		}
		
		// 检查登录状态并加载数据
		this.checkLoginAndLoadData();
	},

	/**
	 * 根据状态设置Tab
	 */
	setTabByStatus(status) {
		let tabIndex = 0;
		
		// 统一为小写字符串，兼容数字字符串
		const s = String(status).toLowerCase();
		switch (s) {
		case '0':
		case 'all':
			tabIndex = 0; // 全部
			break;
		case '1':
		case 'unpaid':
		case 'pending':
			tabIndex = 1; // 待支付
			break;
		case '2':
		case 'done':
		case 'completed':
			tabIndex = 2; // 已完成
			break;
		case '3':
		case 'cancel':
		case 'cancelled':
			tabIndex = 3; // 已取消
			break;
		default:
			tabIndex = 0; // 默认全部
		}
		
		this.setData({
			activeTab: tabIndex
		});
		
		// 若订单数据已存在，立即应用筛选
		if (Array.isArray(this.data.orderList) && this.data.orderList.length > 0) {
			this.filterOrderList();
		}
		
		console.log('设置订单状态Tab：', status, '索引：', tabIndex);
	},

	/**
	 * 获取系统信息
	 */
	getSystemInfo() {
		const systemInfo = wx.getSystemInfoSync();
		this.setData({
			statusBarHeight: systemInfo.statusBarHeight || 44
		});
	},

	/**
	 * 返回上一页
	 */
	onBack() {
		wx.navigateBack({
			delta: 1,
			success: () => {
				console.log('返回上一页成功');
			},
			fail: (error) => {
				console.error('返回上一页失败:', error);
				// 降级处理：跳转到首页
				wx.switchTab({
					url: '/pages/home/index/index'
				});
			}
		});
	},

	/**
	 * 检查登录状态并加载数据
	 */
	async checkLoginAndLoadData() {
		if (!auth.checkLoginStatus()) {
			// 未登录，显示提示并跳转到登录页
			wx.showModal({
				title: '请先登录',
				content: '查看订单列表需要先登录账号',
				confirmText: '去登录',
				cancelText: '返回',
				success: (res) => {
					if (res.confirm) {
						auth.requireLogin('/pages/pay/order-list/index');
					} else {
						wx.navigateBack({
							delta: 1,
							fail: () => {
								wx.switchTab({
									url: '/pages/home/index/index'
								});
							}
						});
					}
				}
			});
			return;
		}
		
		// 已登录，加载订单数据
		await this.loadOrderList();
	},

	/**
	 * 使用缓存加载订单列表数据
	 */
	async loadOrderListWithCache(forceRefresh = false) {
		this.setData({
			isLoading: true
		});

		try {
			const dataManager = app.getDataManager();
			// 使用DataManager获取订单列表，优先使用缓存
			// 传递空对象作为params，forceRefresh作为第二个参数
			const orderData = await dataManager.getOrderList({}, forceRefresh);
			
			if (orderData && orderData.list) {
				const orderList = this.transformAppointmentsToOrders(orderData.list);
				this.setData({
					orderList: orderList,
					isLoading: false
				});
				// 应用当前筛选条件
				this.filterOrderList();
			} else {
				this.setData({
					orderList: [],
					isLoading: false
				});
				this.filterOrderList();
			}

		} catch (error) {
			console.error('加载订单列表失败:', error);
			this.setData({
				isLoading: false
			});
			wx.showToast({
				title: '加载失败',
				icon: 'none'
			});
		}
	},

	/**
	 * 加载订单列表数据（兼容旧方法）
	 */
	async loadOrderList() {
		return await this.loadOrderListWithCache();
	},

	/**
	 * 将预约数据转换为订单格式
	 */
	transformAppointmentsToOrders(appointments) {
		const orders = appointments.map(appointment => {
			const status = this.getOrderStatus(appointment.status);
			const orderTypeInfo = this.getOrderTypeInfo(appointment.orderType);
			
			// 根据订单类型显示不同的信息
			if (appointment.orderType === 'recharge') {
				// 统一处理时间戳（支持秒/毫秒），充值订单按支付时间排序，若无支付时间则使用创建时间
				const sortTime = (() => {
					const ts = this.getPayTimeTs(appointment) || appointment.createTime || 0;
					if (!ts) return 0;
					const n = typeof ts === 'number' ? ts : parseInt(ts, 10);
					if (isNaN(n)) return 0;
					return n >= 1e12 ? n : n * 1000;
				})();
				const details = [];
				// 显示时间行：优先显示支付时间，否则显示创建时间
				const displayTimeTs = this.getPayTimeTs(appointment) || appointment.createTime;
				details.push({ label: orderTypeInfo.timeLabel, value: this.formatDate(displayTimeTs) });
				// 若有支付时间，额外展示“支付时间”行
				const payTsMs = this.getPayTimeTs(appointment);
				if (payTsMs) {
					details.push({ label: '支付时间', value: this.formatDate(payTsMs) });
				}
				// 金额
				details.push({ label: '支付金额', value: `¥${(appointment.rechargeInfo.amount / 100).toFixed(2)}` });
				return {
					id: appointment._id,
					storeName: orderTypeInfo.name,
					status: status.code,
					statusText: status.text,
					type: 'recharge',
					icon: orderTypeInfo.icon,
					bgColor: status.bgColor,
					details: details,
					amount: appointment.rechargeInfo.amount / 100, // 真实订单金额
					amountLabel: status.amountLabel,
					buttons: this.getRechargeOrderButtons(appointment.status),
					appointmentNumber: appointment.appointmentNumber,
					originalData: appointment, // 保存原始数据用于支付
					sortTime: sortTime
				};
			} else {
				// 预约订单
				// 兼容不同结构的 petInfo，避免类型错误
				let petNames = '未知宠物';
				if (Array.isArray(appointment.petInfo)) {
					petNames = appointment.petInfo.map(pet => (pet && pet.name) ? pet.name : '未知').join('、');
				} else if (appointment.petInfo && typeof appointment.petInfo === 'object') {
					petNames = appointment.petInfo.name || '未知宠物';
				}
				
				// 列表排序根据支付时间进行，若无支付时间则使用更新时间，其次创建时间回退
				const sortTime = (() => {
					const ts = this.getPayTimeTs(appointment) || appointment.updateTime || appointment.createTime || 0;
					if (!ts) return 0;
					const n = typeof ts === 'number' ? ts : parseInt(ts, 10);
					if (isNaN(n)) return 0;
					return n >= 1e12 ? n : n * 1000;
				})();
				// 构建详情行：有实际支付时间时展示“支付时间”
				const primaryTimeValue = appointment.orderType === 'apt' ? this.formatDateYMD(appointment.appointmentTime) : this.formatDate(appointment.appointmentTime);
				const details = [
					{ label: orderTypeInfo.timeLabel, value: primaryTimeValue }
				];
				const payTsMs = this.getPayTimeTs(appointment);
				if (payTsMs) {
					details.push({ label: '支付时间', value: this.formatDate(payTsMs) });
				}
				details.push({ label: '支付金额', value: `¥${(appointment.payAmount / 100).toFixed(2)}` });
				return {
					id: appointment._id,
					storeName: orderTypeInfo.name,
					status: status.code,
					statusText: status.text,
					type: appointment.orderType,
					icon: orderTypeInfo.icon,
					bgColor: status.bgColor,
					details: details,
					amount: appointment.payAmount / 100, // 真实订单金额
					amountLabel: status.amountLabel,
					buttons: status.buttons,
					appointmentNumber: appointment.appointmentNumber,
					originalData: appointment, // 保存原始数据用于支付
					sortTime: sortTime
				};
			}
		});
		// 最新订单排在最上面
		orders.sort((a, b) => (b.sortTime || 0) - (a.sortTime || 0));
		return orders;
	},

	/**
	 * 获取订单类型信息
	 */
	getOrderTypeInfo(orderType) {
		switch (orderType) {
			case 'recharge':
				return {
					name: '账户充值',
					icon: '/assets/order-list/icon_recharge.png',
					timeLabel: '充值时间'
				};
			case 'dev':
				return {
					name: '设备使用',
					icon: '/assets/order-list/icon_service.png',
					timeLabel: '启用时间'
				};
			case 'apt':
				return {
					name: '寄养订单',
					icon: '/assets/order-list/icon_foster_care.png',
					timeLabel: '寄养时间'
				};
			case 'beauty':
				return {
					name: '美容预约',
					icon: '/assets/order-list/icon_service.png',
					timeLabel: '预约时间'
				};
			default:
				return {
					name: '寄养订单',
					icon: '/assets/order-list/icon_foster_care.png',
					timeLabel: '寄养时间'
				};
		}
	},

	/**
	 * 获取充值订单操作按钮
	 */
	getRechargeOrderButtons(status) {
		switch (status) {
			case 101: // 待支付
				return [
					{ text: '取消订单', action: 'cancel', type: 'default' },
					{ text: '立即支付', action: 'pay', type: 'primary' }
				];
			case 302: // 已完成（充值成功）
				return [
					{ text: '再次充值', action: 'reorder', type: 'primary' }
				];
			case 401: // 已取消/失败
				return [
					{ text: '重新充值', action: 'reorder', type: 'primary' }
				];
			default:
				return [];
		}
	},

	/**
	 * 获取订单状态信息
	 */
	getOrderStatus(appointmentStatus) {
		switch (appointmentStatus) {
			case 101: // 待支付
				return {
					code: 1,
					text: '待支付',
					bgColor: '#FFF4DD',
					amountLabel: '待支付',
					buttons: [
						{ text: '取消订单', type: 'secondary', action: 'cancel' },
						{ text: '支付订单', type: 'primary', action: 'pay' }
					]
				};
			case 201: // 已支付/待服务
				return {
					code: 2,
					text: '待服务',
					bgColor: '#E1F1FF',
					amountLabel: '已支付',
					buttons: [
						{ text: '查看详情', type: 'primary', action: 'detail' }
					]
				};
			case 301: // 服务中
				return {
					code: 2,
					text: '服务中',
					bgColor: '#E1F1FF',
					amountLabel: '已支付',
					buttons: [
						{ text: '查看详情', type: 'primary', action: 'detail' }
					]
				};
			case 302: // 已完成
				return {
					code: 2,
					text: '已完成',
					bgColor: '#ECFFF5',
					amountLabel: '已支付',
					buttons: [
						{ text: '查看详情', type: 'secondary', action: 'detail' },
						{ text: '再次预约', type: 'primary', action: 'reorder' }
					]
				};
			case 401: // 已取消
				return {
					code: 3,
					text: '已取消',
					bgColor: '#F5F5F5',
					amountLabel: '已取消',
					buttons: [
						{ text: '删除订单', type: 'primary', action: 'delete' }
					]
				};
			default:
				return {
					code: 0,
					text: '未知状态',
					bgColor: '#F5F5F5',
					amountLabel: '未知',
					buttons: []
				};
		}
	},

	/**
	 * 格式化日期
	 */
	formatDate(timestamp) {
		if (!timestamp) return '';
		try {
			// 允许字符串日期或时间戳（秒/毫秒），并兼容 iOS '-' 解析偏差
			let dateObj = null;
			if (typeof timestamp === 'string') {
				let tsStr = timestamp.trim();
				// iOS 对 'YYYY-MM-DD' 的解析可能按 UTC 导致时区偏差，统一替换为 '/'
				if (tsStr.includes('-') && !tsStr.includes('T')) {
					tsStr = tsStr.replace(/-/g, '/');
				}
				const d = new Date(tsStr);
				if (!isNaN(d.getTime())) {
					dateObj = d;
				}
			}
			if (!dateObj) {
				const n = typeof timestamp === 'number' ? timestamp : parseInt(timestamp, 10);
				if (isNaN(n)) return '';
				const ms = n >= 1e12 ? n : n * 1000; // 13位视为毫秒，10位视为秒
				dateObj = new Date(ms);
			}
			const year = dateObj.getFullYear();
			const month = String(dateObj.getMonth() + 1).padStart(2, '0');
			const day = String(dateObj.getDate()).padStart(2, '0');
			const hours = String(dateObj.getHours()).padStart(2, '0');
			const minutes = String(dateObj.getMinutes()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}`;
		} catch (e) {
			console.warn('时间格式化失败:', e, timestamp);
			return '';
		}
	},

	/**
	 * 搜索输入处理
	 */
	onSearchInput(e) {
		const searchText = e.detail.value;
		this.setData({
			searchText: searchText
		});
		// 实时搜索
		this.filterOrderList();
	},

	/**
	 * Tab切换
	 */
	onTabChange(e) {
		const index = e.currentTarget.dataset.index;
		this.setData({
			activeTab: index
		});
		this.filterOrderList();
	},

	/**
	 * 筛选订单列表
	 */
	filterOrderList() {
		const { orderList, activeTab, searchText } = this.data;
		let filteredList = [...orderList];

		// 按状态筛选（activeTab: 0全部 1待支付 2已完成 3已取消；status为数值代码）
		if (activeTab !== 0) {
			filteredList = filteredList.filter(order => order.status === activeTab);
		}

		// 关键字搜索（门店名或预约号）
		if (searchText && searchText.trim()) {
			const kw = searchText.trim();
			filteredList = filteredList.filter(o => (o.storeName && o.storeName.includes(kw)) || (o.appointmentNumber && o.appointmentNumber.includes(kw)));
		}

		// 排序：按支付时间优先排序（sortTime 在转换阶段已按 payTime/updateTime/createTime 统一为毫秒）
		filteredList.sort((a, b) => (b.sortTime || 0) - (a.sortTime || 0));

		this.setData({
			filteredOrderList: filteredList,
			isEmpty: filteredList.length === 0
		});
	},


	/**
	 * 订单按钮点击处理
	 */
	onOrderAction(e) {
		const { action, id } = e.currentTarget.dataset;
		
		switch (action) {
			case 'reorder':
				this.handleReorder(id);
				break;
			case 'cancel':
				this.handleCancelOrder(id);
				break;
			case 'pay':
				this.handlePayOrder(id);
				break;
			case 'delete':
				this.handleDeleteOrder(id);
				break;
			case 'detail':
				// 跳转到订单详情页面
				const order = this.data.filteredOrderList.find(o => o.id === id) || this.data.orderList.find(o => o.id === id);
				if (!order) {
					wx.showToast({ title: '订单信息不存在', icon: 'none' });
					return;
				}
				wx.navigateTo({
					url: `/pages/pay/order-detail/index?appointmentId=${order.id}`
				});
				break;
		}
	},

	/**
	 * 再次预约/充值
	 */
	handleReorder(orderId) {
		console.log('再次预约/充值:', orderId);
		
		// 查找订单信息
		const order = this.data.filteredOrderList.find(o => o.id === orderId);
		if (!order) {
			wx.showToast({
				title: '订单信息不存在',
				icon: 'none'
			});
			return;
		}
		
		if (order.type === 'recharge') {
			// 充值订单 - 跳转到充值页面
			wx.navigateTo({
				url: '/pages/pay/recharge/index'
			});
		} else {
			// 预约订单 - 跳转到服务预约页面
			wx.showToast({
				title: '跳转预约页面',
				icon: 'none'
			});
			// TODO: 实现预约页面跳转
		}
	},

	/**
	 * 取消订单
	 */
	handleCancelOrder(orderId) {
		wx.showModal({
			title: '确认取消',
			content: '确定要取消这个订单吗？',
			success: (res) => {
				if (res.confirm) {
					this.cancelOrder(orderId);
				}
			}
		});
	},

	/**
	 * 支付订单
	 */
	async handlePayOrder(orderId) {
		console.log('支付订单:', orderId);
		
		// 查找订单信息
		const order = this.data.filteredOrderList.find(o => o.id === orderId);
		if (!order) {
			wx.showToast({
				title: '订单信息不存在',
				icon: 'none'
			});
			return;
		}
		
		try {
			wx.showLoading({ title: '处理中...' });
			
			// 先查询用户余额
			const userResult = await apiService.getUserDetail();
			if (!userResult.success) {
				throw new Error('获取用户信息失败');
			}
			
			const userBalance = userResult.data.balance || 0; // 用户余额（分）
			const orderAmount = Math.round(order.amount * 100); // 订单金额（分）
			
			console.log('用户余额:', userBalance, '订单金额:', orderAmount);
			
			if (userBalance >= orderAmount) {
				// 余额充足，尝试余额支付
				const balancePayRes = await this.payWithBalance(orderId, order.type);
				if (!balancePayRes || balancePayRes.paid !== true) {
					// 余额支付失败或后端返回非成功，平滑降级到微信支付，不弹错误提示
					await this.payWithWechat(orderId, order.type);
				}
			} else {
				// 余额不足，直接调起微信支付
				await this.payWithWechat(orderId, order.type);
			}
			
		} catch (error) {
			wx.hideLoading();
			console.error('支付处理失败:', error);
			// 仅在微信支付失败或其它非余额不足错误时提示
			wx.showToast({
				title: error.message || '支付失败',
				icon: 'none'
			});
		}
	},
	
	/**
	 * 余额支付
	 */
	async payWithBalance(orderId, orderType) {
		try {
			let result;
			
			if (orderType === 'recharge') {
				// 充值订单不支持余额支付
				wx.showToast({
					title: '充值订单不支持余额支付',
					icon: 'none'
				});
				return;
			} else {
				// 预约订单余额支付
				result = await apiService.balancePay(orderId);
			}
			
			if (result.success) {
				wx.hideLoading();
				wx.showToast({
					title: '支付成功',
					icon: 'success'
				});
				
				// 刷新订单列表
				await this.loadOrderList();
				return { paid: true };
			} else {
				// 不抛错，返回失败标记，交由上层决定是否走微信支付
				return { paid: false, code: result.code, message: result.message };
			}
			
		} catch (error) {
			wx.hideLoading();
			// 不抛错，返回失败标记
			return { paid: false, message: error.message };
		}
	},
	
	/**
	 * 微信支付
	 */
	async payWithWechat(orderId, orderType) {
		try {
			let paymentResult;
			
			if (orderType === 'recharge') {
				// 充值订单微信支付
				const orderData = {
					description: '账户充值',
					amount: Math.round(this.data.filteredOrderList.find(o => o.id === orderId).amount * 100),
					out_trade_no: `recharge_${orderId}_${Date.now()}`,
					notify_url: 'https://your-domain.com/api/payment/recharge/notify'
				};
				paymentResult = await apiService.createWxPayOrder(orderData);
			} else {
				// 预约订单微信支付
				paymentResult = await apiService.createPayment(orderId);
			}
			
			if (paymentResult.success) {
				// 调起微信支付
				const params = apiService.normalizeWxPaymentParams(paymentResult.data);
				if (params.testMode) {
					wx.hideLoading();
					wx.showToast({ title: '模拟支付成功', icon: 'success' });
					// 云函数模式下，主动回调通知后端
					if (!setting.USE_SELF_BACKEND_PAYMENT) {
						try {
							if (orderType === 'recharge') {
								await apiService.handleRechargeCallback(orderId, { paymentResult: { status: 'success', testMode: true } });
							} else {
								await apiService.handlePaymentCallback(orderId, { paymentResult: { status: 'success', testMode: true } });
							}
						} catch (e) {
							console.warn('模拟支付回调调用失败:', e);
						}
					}
					await this.loadOrderList();
					return;
				}
				const payResult = await wx.requestPayment({
					timeStamp: params.timeStamp,
					nonceStr: params.nonceStr,
					package: params.package,
					signType: params.signType,
					paySign: params.paySign
				});
				
				wx.hideLoading();
				wx.showToast({
					title: '支付成功',
					icon: 'success'
				});
				
				// 支付成功后通知后端更新状态（云函数模式下）
				if (!setting.USE_SELF_BACKEND_PAYMENT) {
					try {
						if (orderType === 'recharge') {
							await apiService.handleRechargeCallback(orderId, { paymentResult: { status: 'success' } });
						} else {
							await apiService.handlePaymentCallback(orderId, { paymentResult: { status: 'success' } });
						}
					} catch (e) {
						console.warn('支付成功回调调用失败:', e);
					}
				}
				
				// 刷新订单列表
				await this.loadOrderList();
				
			} else {
				throw new Error(paymentResult.message || '创建支付订单失败');
			}
			
		} catch (error) {
			wx.hideLoading();
			if (error.errMsg && error.errMsg.includes('cancel')) {
				wx.showToast({
					title: '支付已取消',
					icon: 'none'
				});
			} else {
				throw error;
			}
		}
	},

	/**
	 * 删除订单
	 */
	handleDeleteOrder(orderId) {
		wx.showModal({
			title: '确认删除',
			content: '确定要删除这个订单吗？删除后无法恢复。',
			success: (res) => {
				if (res.confirm) {
					this.deleteOrder(orderId);
				}
			}
		});
	},

	/**
	 * 执行取消订单
	 */
	async cancelOrder(orderId) {
		// 验证登录状态
		if (!auth.checkLoginStatus()) {
			wx.showModal({
				title: '登录已过期',
				content: '请重新登录后再试',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						auth.requireLogin('/pages/pay/order-list/index');
					}
				}
			});
			return;
		}

		try {
			wx.showLoading({ title: '取消中...' });
			
			// 调用取消订单API
			const result = await apiService.cancelAppointment(orderId);
			
			if (result.success) {
				// 更新本地数据，并立即更新视图
				const updatedOrderList = this.data.orderList.map(order => {
					if (order.id === orderId) {
						const cancelledStatus = this.getOrderStatus(401);
						return {
							...order,
							status: cancelledStatus.code,
							statusText: cancelledStatus.text,
							bgColor: cancelledStatus.bgColor,
							amountLabel: cancelledStatus.amountLabel,
							buttons: cancelledStatus.buttons
						};
					}
					return order;
				});

				// 重新应用筛选逻辑到更新后的列表
				const { activeTab, searchText } = this.data;
				let filteredList = updatedOrderList;
				if (activeTab !== 0) {
					filteredList = filteredList.filter(order => order.status === activeTab);
				}
				if (searchText && searchText.trim()) {
					const kw = searchText.trim();
					filteredList = filteredList.filter(o => (o.storeName && o.storeName.includes(kw)) || (o.appointmentNumber && o.appointmentNumber.includes(kw)));
				}

				this.setData({
					orderList: updatedOrderList,
					filteredOrderList: filteredList,
					isEmpty: filteredList.length === 0
				});
				
				wx.hideLoading();
				wx.showToast({
					title: '订单已取消',
					icon: 'success'
				});
			} else {
				throw new Error(result.message);
			}

		} catch (error) {
			wx.hideLoading();
			wx.showToast({
				title: '取消失败',
				icon: 'none'
			});
		}
	},

	/**
	 * 执行删除订单
	 */
	async deleteOrder(orderId) {
		// 验证登录状态
		if (!auth.checkLoginStatus()) {
			wx.showModal({
				title: '登录已过期',
				content: '请重新登录后再试',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						auth.requireLogin('/pages/pay/order-list/index');
					}
				}
			});
			return;
		}

		try {
			wx.showLoading({ title: '删除中...' });
			
			// 查找订单信息，确认订单类型
			const order = this.data.orderList.find(o => o.id === orderId);
			if (!order) {
				throw new Error('订单不存在');
			}
			
			// 只有已取消的订单可以删除
			if (order.status !== 3) { // 3表示已取消
				throw new Error('只有已取消的订单可以删除');
			}
			
			// 调用后端API删除订单（软删除）
			if (order.type !== 'recharge') {
				// 预约订单，调用删除预约接口
				const result = await apiService.deleteAppointment(orderId);
				if (!result.success) {
					throw new Error(result.message || '删除订单失败');
				}
			} else {
				// 充值订单暂不支持删除，只从列表中移除
				console.log('充值订单暂不支持删除');
			}
			
			// 更新本地数据，直接移除已删除的订单
      const updatedOrderList = this.data.orderList.filter(o => o.id !== orderId);
      this.setData({ 
        orderList: updatedOrderList,
        filteredOrderList: this.data.filteredOrderList.filter(o => o.id !== orderId)
      });

      // 如果列表为空，显示空状态
      if (this.data.filteredOrderList.length === 0) {
        this.setData({ isEmpty: true });
      }
			
			wx.hideLoading();
			wx.showToast({
				title: '订单已删除',
				icon: 'success'
			});

		} catch (error) {
			wx.hideLoading();
			console.error('删除订单失败:', error);
			wx.showToast({
				title: error.message || '删除失败',
				icon: 'none'
			});
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	async onShow() {
		// 返回详情页时不刷新列表：使用一次性标记跳过刷新
		const skipOnce = wx.getStorageSync('skipOrderListRefreshOnce');
		if (skipOnce) {
			wx.removeStorageSync('skipOrderListRefreshOnce');
			return; // 直接返回，不触发刷新
		}

		// 验证登录状态
		const isLoggedIn = await auth.validateLoginStatus();
		if (isLoggedIn) {
			// 使用缓存加载订单列表，避免每次都刷新
			await this.loadOrderListWithCache();
		} else {
			// 登录状态失效，重新检查
			this.checkLoginAndLoadData();
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {
		// 下拉刷新时强制从服务器获取最新数据
		this.loadOrderListWithCache(true).then(() => {
			wx.stopPullDownRefresh();
		});
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {
		// TODO: 实现分页加载
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {
		return {
			title: 'PowerPet - 订单列表',
			path: '/pages/pay/order-list/index'
		};
	},

	// 提取订单支付时间（统一返回毫秒，兼容多种字段及字符串/秒/毫秒）
	getPayTimeTs(appointment) {
		const candidates = [
			appointment && appointment.payTime,
			appointment && appointment.paymentTime,
			appointment && appointment.serviceInfo && appointment.serviceInfo.payTime,
			appointment && appointment.serviceInfo && appointment.serviceInfo.paymentTime
		];
		for (let ts of candidates) {
			if (ts === undefined || ts === null || ts === 0) continue;
			if (typeof ts === 'number') {
				return ts >= 1e12 ? ts : ts * 1000;
			}
			if (typeof ts === 'string') {
				let s = ts.trim();
				if (!s) continue;
				if (s.includes('-') && !s.includes('T')) s = s.replace(/-/g, '/');
				const d = new Date(s);
				if (!isNaN(d.getTime())) return d.getTime();
				const n = parseInt(s, 10);
				if (!isNaN(n)) return n >= 1e12 ? n : n * 1000;
			}
		}
		return 0;
	},

    // 仅格式化为年月日
    formatDateYMD(timestamp) {
        if (!timestamp) return '';
        try {
            let dateObj = null;
            if (typeof timestamp === 'string') {
                let tsStr = timestamp.trim();
                if (tsStr.includes('-') && !tsStr.includes('T')) {
                    tsStr = tsStr.replace(/-/g, '/');
                }
                const d = new Date(tsStr);
                if (!isNaN(d.getTime())) {
                    dateObj = d;
                }
            }
            if (!dateObj) {
                const n = typeof timestamp === 'number' ? timestamp : parseInt(timestamp, 10);
                if (isNaN(n)) return '';
                const ms = n >= 1e12 ? n : n * 1000; // 13位视为毫秒，10位视为秒
                dateObj = new Date(ms);
            }
            const year = dateObj.getFullYear();
            const month = String(dateObj.getMonth() + 1).padStart(2, '0');
            const day = String(dateObj.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        } catch (e) {
            console.warn('日期格式化失败:', e, timestamp);
            return '';
        }
    }
})